package com.example.zhangjingyu

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.zhangjingyu.R
import java.io.File

class SecondFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.second_frag, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val editText = view.findViewById<EditText>(R.id.editText)
        val button = view.findViewById<Button>(R.id.button2)

        button.setOnClickListener {
            val inputText = editText.text.toString()
            if (inputText.isNotEmpty()) {
                saveWordToFile(inputText)
                Toast.makeText(requireContext(), "添加的单词: $inputText", Toast.LENGTH_SHORT).show()
                editText.text.clear()
            } else {
                Toast.makeText(requireContext(), "请输入一个单词", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun saveWordToFile(word: String) {
        val file = File(requireContext().filesDir, "words.txt")
        file.appendText("$word\n")
    }
}